/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.explorer.ftypes;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.json.JSONObject;
import org.webos.java.base.Frame;
import org.webos.java.base.fs.FileDescriptor;
import org.webos.java.base.fs.FileType;
import org.webos.java.explorer.Explorer;
import org.webos.java.root.Log;
import org.webos.java.base.fs.FileException;

/**
 *
 * @author kostya
 */
public class TextFileType implements FileType{

    public String getCode() {
        return "text/plain";
    }

    public String getName() {
        return "Text file";
    }

    public String getDescription() {
        return getName();
    }

    public boolean isPlainFile() {
        return true;
    }

    public Object getEditor(FileDescriptor file, Explorer explorer) {
        return new TextEditor(explorer, file);
    }

    public String getViewerClass(FileDescriptor aFile){
        return "explorer.TextViewer";
    }

    public JSONObject getViewer(FileDescriptor file){
        //Read file here
        try {
            JSONObject obj = new JSONObject();
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = 
                    new BufferedReader(new InputStreamReader(file.getProvider().getInputStream(file), "utf-8"));
            String data = null;
            while((data = reader.readLine())!=null){
                buffer.append(data+"\n");
            }
            obj.put("text", buffer.toString());
            reader.close();
            return obj;
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return null;
    }

    public boolean isSystemType() {
        return false;
    }

    public JSONObject messageFromViewer(JSONObject aData, FileDescriptor aFile, Explorer explorer) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public String getIcon() {
        return "explorer_icn explorer_icn_text_file";
    }

    public String[] getExtensions() {
        return new String[]{".txt", ".xml", ".bat", ".sh", ".log"};
    }

}
